package com.py.credit.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.socket.server.standard.SpringConfigurator;

// 手机扫码人脸认证后通知页面
@ServerEndpoint(value = "/ws/websocket/{clientId}", configurator = SpringConfigurator.class)
public class WebSocketServer {

	// 已经建立链接的对象缓存起来
	private static ConcurrentMap<String, WebSocketServer> serverMap = new ConcurrentHashMap<String, WebSocketServer>();
	// 当前session
	private Session currentSession;

	@OnOpen
	public void onOpen(@PathParam(value = "clientId") String clientId, Session session) throws IOException {

		serverMap.put(clientId, this);

		this.currentSession = session;

	}

	@OnClose
	public void onClose(Session session, CloseReason reason) {

		this.currentSession = null;
		try {
			session.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@OnMessage
	public void onMessage(String message) {

	}

	public Session getCurrentSession() {
		return currentSession;
	}

	@OnError
	public void onError(Throwable t) {
		t.printStackTrace();
	}

	public static void sendMessage(String clientId, String message) {

		WebSocketServer webSocketServer = serverMap.get(clientId);

		Session session = webSocketServer.getCurrentSession();

		if (session != null && session.isOpen()) {

			try {
				session.getBasicRemote().sendText(message);
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}
